<template>
    <div class="container">
        <lemon-imui ref="IMUI"
                    @pull-messages='handlePullMessages'
                    :user="user" @send="handleSend"
                    :hideMenu="true"
                    :width="'100%'"
                    :height="'100%'"
                    :contextmenu="contextmenu"
                    :contactTimeFormat="format"
                    :messageTimeFormat="format"
                    @message-click="handleMessagesClick"

        />
        <el-image-viewer v-if="imgViewerVisible" :on-close="closeImgViewer" :url-list="imgList" />
        <el-dialog
            :visible.sync="videoVisible"
            width="50%"
            :show-close="false"
            destroy-on-close
        >
            <video-player
                class="video-player vjs-custom-skin"
                ref="videoPlayer"
                :playsinline="true"
                :options="playerOptions"/>
        </el-dialog>



    </div>
</template>

<script>
import user from '@/database/user'
import emoji from '@/database/emoji'
import contacts from "@/database/contacts";
import post from '@/utils/upload'
const generateUUID = () => {
    var d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
    }
    var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(
        c,
    ) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
    });
    return uuid;
}

export default {
    name: "Home",
    components: {
        'el-image-viewer':()=>import('element-ui/packages/image/src/image-viewer')
    },
    data() {
        return {
            webSocket: null,
            user: null,
            isOk: false,
            message: null,
            IMUI: null,
            contacts: [],
            contextmenu: null,
            format: null,
            imgViewerVisible: false, //图片预览打开标志
            imgList: [], //图片预览路径数组
            videoUrl: null,
            videoVisible: false,//视频预览打开标志
            playerOptions: {
                playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
                autoplay: false, //如果true,浏览器准备好时开始回放。
                muted: false, // 默认情况下将会消除任何音频。
                loop: false, // 导致视频一结束就重新开始。
                preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
                language: 'zh-CN',
                aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
                fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
                sources: [{
                    type: "video/mp4",// 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
                    src: "" // url地址
                }],
                poster: "", // 你的封面地址
                notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
                controlBar: {
                    timeDivider: true,
                    durationDisplay: true,
                    remainingTimeDisplay: false,
                    fullscreenToggle: true  // 全屏按钮
                }
            }
        }
    },
    created() {
        this.format = (time) => {
            let toData = new Date(new Date().toLocaleDateString()).getTime()

            //今天
            let todayStart = toData //开始时间
            let todayEnd = todayStart + 24 * 60 * 60 * 1000 - 1 //结束时间
            let date = new Date(time)
            if (time >= todayStart && time <= todayEnd) {
                return `${date.getHours()}:${date.getMinutes()}`
            }
            //昨天
            let yesterdayStart = toData - 3600 * 24 * 1000
            let yesterdayEnd = (yesterdayStart) + 24 * 60 * 60 * 1000 - 1
            if (time >= yesterdayStart && time <= yesterdayEnd) {
                return `昨天 ${date.getHours()}:${date.getMinutes()}`
            } else {
                return `${date.getFullYear() - 2000}/${date.getMonth() + 1}/${date.getDate()}`
            }
        }
        this.user = user[this.$route.query.id]
        this.contextmenu = this.initContextmenu()
        this.loadContacts()
    },
    mounted() {
        let tools = [
            {
                name: "emoji",
                title: "发送表情",
            },
            {
                name: "uploadImage",
                title: "发送图片"
            },
            {
                name: "uploadFile",
                title: "发送文件",
            },
            {
                name: "uploadVideo",
                title: "发送视频",
                click: () => {
                    var uploadVideo = this.$refs.uploadVideo;
                    uploadVideo.click();
                },
                render: () => {
                    return <i class="el-icon-video-play" style="vertical-align: middle;font-size: 18px;">
                        <input id="video" style="display:none" type="file" accept="video/*" ref="uploadVideo" on-change={e => {
                            this.uploadVideo(e);
                        }} /></i>
                }
            },
        ];
        this.initWebSocket()
        const {IMUI} = this.$refs;
        IMUI.initEmoji(emoji)
        this.IMUI = IMUI;
        IMUI.setLastContentRender('video', message  => {
            return "[视频]"
        })
        IMUI.initEditorTools(tools)
        console.log("666")

    },
    destroyed() {
        if (this.webSocket) {
            this.webSocket.close()
        }
    },
    methods: {
        doProgress (val) {
            this.$refs.videoPlayer.currentTime(val)
            this.$refs.videoPlayer.play()
        },
        /**
         * 视频上传
         * @param e
         */
        async uploadVideo(e) {
            let file = e.srcElement.files[0];
            let url = URL.createObjectURL(file);
            let id = this.IMUI.getCurrentContact().id
            let message = {
                content: url,
                fromUser: this.user,
                id: generateUUID(),
                sendTime: new Date().getTime(),
                status: 'going',
                toContactId: id,
                type: 'video',
            }
            this.IMUI.appendMessage(message,true)
            this.handleSend(message, () => {
                let replaceMessage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
                    status: "succeed"
                };
                this.IMUI.updateContact({
                    id: message.toContactId,
                    lastContent: this.IMUI.lastContentRender(message),
                    lastSendTime: message.sendTime
                });
                this.IMUI.CacheDraft.remove(message.toContactId);
                this.IMUI.updateMessage(Object.assign(message, replaceMessage));
            }, file)
            // 将选择的文件清空
            this.$refs.uploadVideo.value='';
        },
        /**
         * 点击信息事件
         * @param event
         * @param key
         * @param Message
         * @param instance
         */
        handleMessagesClick(event,key,Message,instance) {
           if (Message.type === "image") {
               this.imgList = [Message.content];
               this.imgViewerVisible = true;
               const m = (e) => { e.preventDefault() };
               document.body.style.overflow = 'hidden';
               document.addEventListener("touchmove", m, false); // 禁止页面滑动
           } else if (Message.type === "video") {
               // //获取文件和照片路径
               let urls = JSON.parse(Message.content);
               this.playerOptions.sources[0].src = urls[0]
               this.playerOptions.poster = urls[1]
               this.videoVisible = true
           }
        },
        /**
         * 关闭图片预览弹窗
         */
        closeImgViewer() {
            this.imgViewerVisible = false;
            const m = (e) => { e.preventDefault() };
            document.body.style.overflow = 'auto';
            document.removeEventListener("touchmove", m, true);
        },
        /**
         * 初始化消息右键菜单
         * @returns {*[]}
         */
        initContextmenu() {
            return [
                    {
                        click: (e, instance, hide) => {
                            const { IMUI, message } = instance;
                            const data = {
                                id: generateUUID(),
                                type: "event",
                                //使用 jsx 时 click必须使用箭头函数（使上下文停留在vue内）
                                content: (
                                    <div>
                  <span>
                    你撤回了一条消息{" "}
                      <span
                          v-show={message.type === "text"}
                          style="color:#333;cursor:pointer"
                          content={message.content}
                          onClick={e => {
                              IMUI.setEditorValue(e.target.getAttribute("content"));
                          }}
                      >
                      重新编辑
                    </span>
                  </span>
                                    </div>
                                ),

                                toContactId: message.toContactId,
                                sendTime: new Date().getTime(),
                            };
                            console.log(message)
                            IMUI.removeMessage(message.id);
                            IMUI.appendMessage(data, true);
                            hide();
                        },
                        visible: instance => {
                            return instance.message.fromUser.id === this.user.id;
                        },
                        text: "撤回消息",
                    },
                    {
                        click: (e, instance, hide) => {
                            const { message } = instance;
                            navigator.clipboard.writeText(message.content);
                            this.$message.info("复制成功！")
                            hide();
                        },
                        visible: instance => {
                            return instance.message.type === "text";
                        },
                        text: "复制文字",
                    },
                    {
                        visible: instance => {
                            return instance.message.type === "image";
                        },
                        text: "下载图片",
                    },
                    {
                        visible: instance => {
                            return instance.message.type === "file";
                        },
                        text: "下载文件",
                    },
                    {
                        click: (e, instance, hide) => {
                            const { IMUI, message } = instance;
                            this.$request.delete(`/message/delete`,message).then(res => {
                                if (res.code === '200') {
                                    this.$message.success('删除成功')
                                    IMUI.removeMessage(message.id);
                                    hide();
                                } else {
                                    this.$message.error(res.msg)
                                }
                            })
                        },
                        icon: "lemon-icon-folder",
                        color: "red",
                        text: "删除",
                    },
                ]
        },
        loadContacts() {
            this.$request.get(`/contact/getContactByUserId?id=${this.user.id}`).then(res => {
                this.contacts = res.data || [];
                console.log('联系人', this.contacts)
                this.IMUI.initContacts(this.contacts)
            })
        },
        initWebSocket() {
            if (!this.webSocket && this.user.id) {
                this.webSocket = new WebSocket(`ws://localhost:9090/websocket/${this.user.id}`)
                this.webSocket.onopen = () => {
                    console.log('websocket连接成功')
                }
                this.webSocket.onmessage = (event) => {
                    this.message = JSON.parse(event.data)
                    if (this.message.toContactId === this.user.id) {
                        //添加信息
                        let message = this.message
                        message.toContactId = this.message.fromUser.id
                        this.IMUI.appendMessage(message, true)
                    }
                    console.log(this.message)
                }
                this.webSocket.onclose = () => {
                    console.log('websocket连接关闭')
                }
                this.webSocket.onerror = () => {
                    console.log('websocket连接错误')
                }
                this.webSocket.se
            }
        },
        /**
         * 初次点击联系人触发
         * @param contact
         * @param next
         */
        async handlePullMessages(contact, next) {
            contact.unread = 0;
            this.$request.get(`/message/list`,{
                params: {
                    contactId: contact.id,
                    userId: this.user.id
                }
            }).then(res => {
                const  messages = res.data || []
                next(messages, true);
            })

        },
        /**
         * 发送消息
         * @param message
         * @param next
         * @param file
         */
          handleSend(message, next, file) {
             //向后端发送信息
             if (!file) {
                 this.webSocket.send(JSON.stringify(message))
                 //上传图片
             } else {
                 post(file).then(res => {
                     if (res.data) {
                         if (message.type !== 'video') {
                             message.content = res.data.data[0]
                         } else {
                             //如果是视频，更新视频路径
                             // let content = JSON.parse(message.content);
                             // content[0] = res.data.data;
                             // console.log('视频', content)
                             message.content = JSON.stringify(res.data.data)
                         }
                         this.webSocket.send(JSON.stringify(message))
                     }
                 })
             }
             const timer = setInterval(() => {
                 if (this.message && this.message.id === message.id) {
                     this.message.status = 'succeed'
                     next(this.message)
                     clearInterval(timer)
                     this.message = null
                     let contact = this.IMUI.getCurrentContact()
                     console.log('更新用户数据',contact)
                     this.webSocket.send(JSON.stringify(this.IMUI.getCurrentContact()))
                 }
             }, 1000)

         },
        changContact() {
            this.IMUI.appendContact(contacts[0])
            this.IMUI.changeContact(1)
        }
    }
}
</script>

<style scoped>
.container {
    height: 100vh;
    width: 100%;
    overflow: hidden;
    background-size: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #666;
}

.lemon-editor__emoji-item {
    width: 30px;
}
.f-18 {
    font-size: 18px;
}
/* >>> 穿透组件样式 */
>>> .el-dialog__header {
    display: none !important;
}
>>> .el-dialog__body {
    padding: 0 !important;
}
</style>